clc
% lambda = 70==>78.5%
lambda = 5;
rows = 5;
columns = 5;
%unitWidth = 7.8;
unitWidth = 4.0890*2;

retMatrix = [];
for ii = 1:inf
    
poissonRandomNumbers= poissrnd(lambda, rows,columns);
    for i = 1:rows
        for j = 1:columns % For every poisson random number indicating the total nodes in a region, generate a 2D coordinate for each node. 
            randomCoordinates = rand(poissonRandomNumbers(i,j), 2);
            scalerMatrix = [unitWidth 0; 0 unitWidth];
            for l = 1:poissonRandomNumbers(i,j) % the nodes position is mapped to a larger 2D plane.
                randomCoordinates(l,1) = randomCoordinates(l,1)*unitWidth + (i-1)*unitWidth;
                randomCoordinates(l,2) = randomCoordinates(l,2)*unitWidth + (j-1)*unitWidth;
            end
            retMatrix = [ retMatrix' randomCoordinates']';
        end
    end

    NodesCount = sum(sum(poissonRandomNumbers));
    DesiredLinkCount = 0;
    for it1 = 1:NodesCount
        small_distance = 100;
        for it2 = 1:NodesCount
           if it1 == it2
               continue
           end
           distance = sqrt ((retMatrix(it1,1)-retMatrix(it2,1))^2 + (retMatrix(it1,2)-retMatrix(it2,2))^2);
           distance_it1 = sqrt(retMatrix(it1,1)^2 + retMatrix(it1,2)^2);
           distance_it2 = sqrt(retMatrix(it2,1)^2 + retMatrix(it2,2)^2);
           
           if distance <= 3.4280 %&& distance <= 4.0890
           %if distance <= 3.9050 && distance_it1 >= distance_it2    %%This is for Converge-cast.
               small_distance = distance;
               %DesiredLinkCount = DesiredLinkCount + 1;
               %break;
           end
        end
        if small_distance ~= 100
            DesiredLinkCount = DesiredLinkCount + 1;
        end
    end
    [NodesCount DesiredLinkCount];
    if NodesCount - DesiredLinkCount == 1
    %if DesiredLinkCount/NodesCount == 1
        fileId = fopen('data.txt', 'w');
        fprintf( fileId, '%2.6f %2.6f 0 \n', retMatrix');

        plot(retMatrix(:, 1), retMatrix(: , 2 ), '.')
        %retMatrix(:, 1)
        sum(sum(poissonRandomNumbers))
        break;
    end
    retMatrix = [];
end
